package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.PostCommentListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.DensityUtil;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GetCategory;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.SharesUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.ShopInfoView;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.TextViewExpandableAnimation;
import com.eightbears.beboy.base.view.gif.AnimatedGifDrawable;
import com.eightbears.beboy.base.view.gif.AnimatedImageSpan;
import com.eightbears.beboy.base.view.image.ui.ImageViewActivity;
import com.eightbears.beboy.base.view.image.view.ImageItem;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.layout.WrappableGridLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.base.view.popupwindow.MultipeSelectionPopup;
import com.eightbears.beboy.entity.CommonEntity;
import com.eightbears.beboy.entity.DeleteCommentEntity;
import com.eightbears.beboy.entity.HomeListEntity;
import com.eightbears.beboy.entity.PostCommentsEntity;
import com.eightbears.beboy.entity.PostEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.greendao.Friends;
import com.hyphenate.chat.EMClient;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FAV_UNFAV;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FOLLOW_UNFOLLOW;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_COMMENT_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_DELETE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_DELETE_COMMENT;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_LIKE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SENDPOST;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_COMMENT;
import static com.eightbears.beboy.ui.user.activity.RepostPostActivity.EVENT_PARAMS_LIKE;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.EVENT_BUY_POST_SUCCESS;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_BUY_POST;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ID;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ITEM;

public class PostDetailActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String EVENT_DELETE_POST = "deletePost";

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.ll_btn_like)
    LinearLayout ll_btn_like;
    @BindView(R.id.ll_btn_comment)
    LinearLayout ll_btn_comment;
    @BindView(R.id.ll_btn_repost)
    LinearLayout ll_btn_repost;
    @BindView(R.id.ll_btn_share)
    LinearLayout ll_btn_share;
    @BindView(R.id.tv_comment)
    TextView tv_bottom_comment;
    @BindView(R.id.tv_like)
    TextView tv_bottom_like;
    @BindView(R.id.tv_share)
    TextView tv_bottom_share;
    @BindView(R.id.tv_repost)
    TextView tv_bottom_repost;
    @BindView(R.id.view_bottom)
    View view_bottom;
    @BindView(R.id.view_foot)
    View view_foot;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.activity_post_comment)
    RelativeLayout activity_post_comment;

    // 列表头部信息
    private RoundedImageView iv_user_head;
    private TextView tv_nickname;
    private TextView tv_publish_date;
    private LinearLayout ll_follow_drop_down;
    private Button btn_comment;
    private TextView tv_content_uncollaps;
    private TextView tv_repost_text;
    private TextViewExpandableAnimation tv_content;
    private View view_image;
    private View view_repost;
    private View view_pay;
    private RecyclerView rv_img;
    private UserEntity mUserEntity;
    private LinearLayout ll_empty;
    private ShopInfoView shop_info_view;
    ImageView iv_level;

    // 收费，免费，已买界面
    private ImageView iv_vip;
    private TextView tv_buy_info;
    private TextView tv_category;

    private String[] phones;
    private String postId;
    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private JSONArray faceJson;
    private String lat;
    private String lon;
    private String replyName;

    private PostCommentListAdapter postCommentListAdapter;
    private HomeListEntity.Post postContent;
    private PostCommentsEntity postCommentsEntity;
    private PostCommentsEntity.SubPostComment subPostComment;
    private MultipeSelectionPopup multipeSelectionPopup;
    private PostCommentsEntity.PostComment postComment;
    private InputMethodManager imm;
    private Friends friends;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_comment);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        observe(activity_post_comment);
        tv_title.setText(R.string.text_post_detail);
    }

    @Override
    protected void initData() {
        postId = getIntent().getStringExtra(PARAMS_POST_ID);
        mUserEntity = SPUtil.getUser();
        getDetail();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.ll_btn_comment)
    void comment() {
        postContent.setReport(false);
        startLocalActivity(this, RepostPostActivity.class, PARAMS_POST_ITEM, postContent);
    }

    @OnClick(R.id.ll_btn_repost)
    void repost() {
        postContent.setReport(true);
        startLocalActivity(this, RepostPostActivity.class, PARAMS_POST_ITEM, postContent);
    }

    @OnClick(R.id.ll_btn_like)
    void like() {
        // 赞
        if (postContent.getPraise() == 1) {
            postContent.setPraise(0);
            Drawable drawable = mContext.getResources().getDrawable(R.mipmap.icon_zan_comment);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_bottom_like.setCompoundDrawables(drawable, null, null, null);
        } else {
            postContent.setPraise(1);
            Drawable drawable = mContext.getResources().getDrawable(R.mipmap.icon_zan_home_sel);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_bottom_like.setCompoundDrawables(drawable, null, null, null);
        }
        executeLike();
    }

    @OnClick(R.id.ll_btn_share)
    void shared() {
        SharesUtil.shareContent(PostDetailActivity.this, postContent.getId());
    }

    @OnClick(R.id.btn_send)
    void repostUser() {
        if (!TextUtils.isEmpty(et_content.getText())) {
            RePostUserComment();
        } else {
            ShowToast.showShortToast(R.string.text_content_no_empty);
        }
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        postCommentListAdapter = new PostCommentListAdapter();
        postCommentListAdapter.addHeaderView(getHeaderView());
        postCommentListAdapter.openLoadAnimation();
        postCommentListAdapter.setOnLoadMoreListener(this);
        postCommentListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                postComment = (PostCommentsEntity.PostComment) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.iv_user_head:
                        startLocalActivity(PostDetailActivity.this, UserInfoActivity.class, PARAMS_USER_INFO, postComment.getUser_id());
                        break;
                    case R.id.tv_repost_user:
                        showRepostView();
                        break;

                }
            }
        });

        postCommentListAdapter.setOnSubCommentClickListener(new PostCommentListAdapter.OnClickSubCommentItemListener() {
            @Override
            public void onSubCommentClick(BaseQuickAdapter baseViewHolder, View view, int i, PostCommentsEntity.PostComment mPostComment) {
                postComment = mPostComment;
                subPostComment = (PostCommentsEntity.SubPostComment) baseViewHolder.getData().get(i);
                postComment.getUser().setNickname(subPostComment.getUser().getNickname());
                postComment.getUser().setUser_id(subPostComment.getUser().getUser_id());
                showRepostView();
            }
        });

        postCommentListAdapter.setLongOnSubCommentClickListener(new PostCommentListAdapter.OnLongClickSubCommentItemListener() {
            @Override
            public void onLongSubCommentClick(BaseQuickAdapter baseViewHolder, View view, int i, PostCommentsEntity.PostComment mPostComment) {
                postComment = mPostComment;
                subPostComment = (PostCommentsEntity.SubPostComment) baseViewHolder.getData().get(i);
                showMultipeSelectionPopup();
            }
        });

        rv_list.setAdapter(postCommentListAdapter);
    }


    private View getHeaderView() {

        View view = getLayoutInflater().inflate(R.layout.head_post_comment, null);
        iv_user_head = (RoundedImageView) view.findViewById(R.id.iv_user_head);
        tv_nickname = (TextView) view.findViewById(R.id.tv_nickname);
        iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
        tv_publish_date = (TextView) view.findViewById(R.id.tv_publish_date);
        ll_follow_drop_down = (LinearLayout) view.findViewById(R.id.ll_follow_drop_down);
        tv_content_uncollaps = (TextView) view.findViewById(R.id.tv_content_uncollaps);
        tv_content = (TextViewExpandableAnimation) view.findViewById(R.id.tv_content);
        view_image = view.findViewById(R.id.view_image);
        view_repost = view.findViewById(R.id.view_repost);
        view_pay = view.findViewById(R.id.view_pay);
        rv_img = (RecyclerView) view_image.findViewById(R.id.rv_img);
        ImageView iv_img = (ImageView) view_image.findViewById(R.id.iv_img);
        tv_repost_text = (TextView) view_repost.findViewById(R.id.tv_repost_text);
        tv_buy_info = (TextView) view_pay.findViewById(R.id.tv_buy_info);
        tv_category = (TextView) view.findViewById(R.id.tv_category);
        ll_empty = (LinearLayout) view.findViewById(R.id.ll_empty);
        btn_comment = (Button) view.findViewById(R.id.btn_comment);
        shop_info_view = (ShopInfoView) view.findViewById(R.id.shop_info_view);
        iv_level = (ImageView) view.findViewById(R.id.iv_level);

        initHeadView();
        initHeadViewEvent();
        return view;
    }

    private void initHeadViewEvent() {
        btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postContent.setReport(false);
                startLocalActivity(PostDetailActivity.this, RepostPostActivity.class, PARAMS_POST_ITEM, postContent);
            }
        });

        tv_buy_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(PostDetailActivity.this, PaymentActivity.class, PARAMS_BUY_POST, postContent);
            }
        });

        iv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(PostDetailActivity.this, UserInfoActivity.class, PARAMS_USER_INFO, postContent.getUser_id());
            }
        });

        ll_follow_drop_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dropDownMenu();
            }
        });
    }

    private void initHeadView() {
        CommonUtils.loadImageView(this, postContent.getUser().getCover(), R.mipmap.default_head, iv_user_head);
        tv_nickname.setText(postContent.getUser().getNickname());
        tv_content.setVisibility(View.GONE);
        tv_content_uncollaps.setVisibility(View.VISIBLE);

        if (checkGifExist(postContent.getPost())) {
            tv_content_uncollaps.setText(handler(tv_content_uncollaps, postContent.getPost()));
        } else {
            tv_content_uncollaps.setText(postContent.getPost());
        }
        tv_category.setText("# " + GetCategory.getCategoryNameById(postContent.getCategory()));

        if (postContent.getPraise() == 1) {
            Drawable drawable = mContext.getResources().getDrawable(R.mipmap.icon_zan_home_sel);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_bottom_like.setCompoundDrawables(drawable, null, null, null);
        } else {
            Drawable drawable = mContext.getResources().getDrawable(R.mipmap.icon_zan_comment);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_bottom_like.setCompoundDrawables(drawable, null, null, null);
        }

        if (postContent.getUser().getVip_level() > 0) {
            iv_vip.setVisibility(View.VISIBLE);
            if (postContent.getUser().getVip_level() == 1) {
                iv_vip.setImageResource(R.mipmap.icon_new_vip1);
            } else if (postContent.getUser().getVip_level() == 2) {
                iv_vip.setImageResource(R.mipmap.icon_new_vip2);
            }
        } else {
            iv_vip.setVisibility(View.GONE);
        }


        if (postContent.getPoints() != null) {
            if (postContent.getPoints().getLevel() == 1) {
                iv_level.setImageResource(R.mipmap.icon_level_one);
            } else if (postContent.getPoints().getLevel() == 2) {
                iv_level.setImageResource(R.mipmap.icon_level_two);
            } else if (postContent.getPoints().getLevel() == 3) {
                iv_level.setImageResource(R.mipmap.icon_level_three);
            } else if (postContent.getPoints().getLevel() == 4) {
                iv_level.setImageResource(R.mipmap.icon_level_four);
            } else if (postContent.getPoints().getLevel() == 5) {
                iv_level.setImageResource(R.mipmap.icon_level_five);
            }
            iv_level.setVisibility(View.VISIBLE);
        }

        if (postContent.getRepost() != null) {
            String repostText = mContext.getString(R.string.text_repost_text);
            String formatRepostText = String.format(repostText, postContent.getRepost().getNickname(), postContent.getRepost().getPost());
            Spanned htmlRequestText = Html.fromHtml(formatRepostText);
            if (null != postContent.getRepost().getPost() && !"".equals(postContent.getRepost().getPost())) {
                tv_repost_text.setText(htmlRequestText);
            }
        }

        tv_publish_date.setText(CommonUtils.TimeStamp2Date(postContent.getCreated_at(), "MM-dd"));
        // 图片显示
        showImages();
        // 显示购买信息
        showBuyInfo();
    }

    private void RePostUserComment() {
        String url = URL_POST_COMMENT_LIST + postComment.getPost_id() + "/comment";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("reply_user_id", postComment.getUser().getUser_id() + "")
                .addParams("comment_id", postComment.getId())
                .addParams("comment", et_content.getText().toString().trim())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                if (response.contains(CONNECTION_STATUS_SUCCESS)) {
                    PostCommentsEntity.SubPostComment subPostComment = new PostCommentsEntity.SubPostComment();
                    PostCommentsEntity.CommentUser replyUser = postComment.getUser();
                    PostCommentsEntity.CommentUser user = new PostCommentsEntity.CommentUser();
                    user.setUser_id(mUserEntity.getData().getUser_id());
                    user.setCover(mUserEntity.getData().getCover());
                    user.setNickname(mUserEntity.getData().getNickname());
                    user.setVip_level(mUserEntity.getData().getVip_level());
                    subPostComment.setUser(user);
                    subPostComment.setReply_user(replyUser);
                    subPostComment.setComment(et_content.getText().toString());
                    subPostComment.setUser_id(user.getUser_id());
                    subPostComment.setPost_id(postComment.getPost_id());
                    subPostComment.setComment_id(postComment.getId());
                    List<PostCommentsEntity.SubPostComment> postComments = postComment.getSub_comments().getList();
                    if (null == postComments || postComments.size() < 0) {
                        List<PostCommentsEntity.SubPostComment> newPost = new ArrayList<>();
                        newPost.add(subPostComment);
                        postComment.getSub_comments().setList(newPost);
                    } else {
                        postComment.getSub_comments().getList().add(subPostComment);
                    }
                    postCommentListAdapter.notifyDataSetChanged();
                    EventBus.getDefault().post(EVENT_PARAMS_COMMENT);
                    hideRepostView();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PostDetailActivity.this, status_error);
            }
        });
    }

    private void getDetail() {
        String url = URL_SENDPOST + "/" + postId;
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                PostEntity postEntity = GsonUtil.fromJson(response, PostEntity.class);
                if (postEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    postContent = postEntity.getData();
                    KLog.e(postContent);
                    initAdapter();
                    getData();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PostDetailActivity.this, status_error);
            }
        });
    }

    // 获得评论
    private void getData() {
        swipeLayout.setRefreshing(true);
        String url = URL_POST_COMMENT_LIST + postId + "/comments";
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(PARAMS_PAGE_SIZE))
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);

                postCommentsEntity = GsonUtil.fromJson(response, PostCommentsEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(postCommentsEntity.getStatus_code())) {
                    if (postCommentsEntity.getData().getList().size() == 0) {
                        ll_empty.setVisibility(View.VISIBLE);
                    } else {
                        ll_empty.setVisibility(View.GONE);
                    }
                    isEnd = postCommentsEntity.getData().getIs_end();
                    if (page == 1)
                        postCommentListAdapter.setNewData(postCommentsEntity.getData().getList());
                    else {
                        postCommentListAdapter.addData(postCommentsEntity.getData().getList());
                        postCommentListAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PostDetailActivity.this, status_error);
            }
        });
    }

    /**
     * 点赞
     */
    private void executeLike() {

        String url = URL_POST_LIKE + "/" + postContent.getStatistic().getPost_id() + "/praise";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    EventBus.getDefault().post(EVENT_PARAMS_LIKE);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PostDetailActivity.this, status_error);
            }
        });
    }

    private void showBuyInfo() {
        double price;
        boolean isPurchase = postContent.getPurchase() != null && postContent.getPurchase().size() > 0;
        if (isPurchase || mUserEntity.getData().getVip_level() > 0
                || mUserEntity.getData().getUser_id().equals(postContent.getUser_id())) {
            view_pay.setVisibility(View.GONE);
            showShopInfo();
        } else {
            if (postContent.getRepost() != null) {
                price = postContent.getRepost().getPrice();
            } else {
                price = postContent.getPrice();
            }
            if (price > 0) {
                view_pay.setVisibility(View.VISIBLE);
                String buyExplain = mContext.getResources().getString(R.string.text_purchase_info);
                String formatExplain = String.format(buyExplain, price);
                Spanned htmlExplain = Html.fromHtml(formatExplain);
                tv_buy_info.setText(htmlExplain);
            } else {
                showShopInfo();
            }
        }
    }

    private void showShopInfo() {

        lat = postContent.getLatitude();
        lon = postContent.getLongitude();

        String shopName;
        String shopAddress;
        String shopContact;
        String consumption;
        String date;
        String buyId;
        String nickName;
        if (null == postContent.getRepost()) {
            shopName = postContent.getShop();
            shopAddress = postContent.getAddress();
            shopContact = postContent.getContact();
            consumption = postContent.getConsumption();
            date = postContent.getConsumed_at();
            buyId = postContent.getId();
            nickName = postContent.getUser().getNickname();
        } else {
            view_repost.setVisibility(View.VISIBLE);
            HomeListEntity.Repost homeListRepost = postContent.getRepost();
            nickName = homeListRepost.getNickname();
            buyId = homeListRepost.getId();
            shopName = homeListRepost.getShop();
            shopAddress = homeListRepost.getAddress();
            shopContact = homeListRepost.getContact();
            consumption = homeListRepost.getConsumption();
            date = homeListRepost.getConsumed_at();
        }
        shop_info_view.setVisibility(View.VISIBLE);
        shop_info_view.setShopName(shopName);
        shop_info_view.setShopAddress(shopAddress);
        shop_info_view.setShopPhone(shopContact);
        shop_info_view.setShopPrice(consumption);
        shop_info_view.setShopDate(date);

        shop_info_view.setOnItemClickLinester(new ShopInfoView.OnItemClickListener() {
            @Override
            public void onImageClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_address:
                        LatLng mLatLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lon));
                        CommonUtils.showMapSelView(PostDetailActivity.this, mLatLng);
                        break;
                    case R.id.ll_phone:
                        callShop();
                        break;
                }

            }
        });
    }

    // 显示图片
    private void showImages() {
        if (postContent.getImages() != null && postContent.getImages().size() > 0) {
            view_image.setVisibility(View.VISIBLE);
            rv_img = (RecyclerView) view_image.findViewById(R.id.rv_img);
            initImagesAdapter(postContent.getImages());
        } else if (null != postContent.getRepost() &&
                null != postContent.getRepost().getImages() && postContent.getRepost().getImages().size() > 0) {
            view_image = view_repost.findViewById(R.id.view_image_repost);
            view_repost.setVisibility(View.VISIBLE);
            view_image.setVisibility(View.VISIBLE);
            rv_img = (RecyclerView) view_image.findViewById(R.id.rv_img);
            initImagesAdapter(postContent.getRepost().getImages());
        }
    }

    /**
     * 初始化图片适配
     */
    private void initImagesAdapter(List<String> images) {
        ImagesAdapter mImagesAdapter = new ImagesAdapter();
        WrappableGridLayoutManager mWrapHeightGridLayoutManager = new WrappableGridLayoutManager(mContext, 3);
        rv_img.setLayoutManager(mWrapHeightGridLayoutManager);
        mImagesAdapter.setNewData(ImageItem.replaceImage(images));
        rv_img.setAdapter(mImagesAdapter);
        mImagesAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intentPreview = new Intent(PostDetailActivity.this, ImageViewActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getData());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                startActivity(intentPreview);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
            }
        });
    }

    //图片适配
    private class ImagesAdapter extends BaseQuickAdapter<ImageItem, BaseViewHolder> {
        public ImagesAdapter() {
            super(R.layout.item_image, null);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, ImageItem image) {
            Glide.with(mContext).load(image.path).into((ImageView) baseViewHolder.getView(R.id.iv_item));
            baseViewHolder.addOnClickListener(R.id.iv_item);
        }
    }

    private boolean validPhone() {
        String phone = postContent.getContact();
        phones = phone.split(" ");
        if (phones.length == 0) {
            phones = phone.split("/");
        }
        if (phone.trim().length() < 5)
            return false;

        if (phones.length > 1) {
            if (!CommonUtils.checkTelephone(phones[0]) && !CommonUtils.checkTelephone(phones[1])) {
                return false;
            }
        } else if (!CommonUtils.checkTelephone(phone)) {
            return false;
        }

        return true;
    }

    /**
     * 拨打电话
     */
    private void callShop() {

        if (!validPhone()) {
            ShowToast.showShortToast(getString(R.string.text_cantact_empty));
            return;
        }
        BottomSelectionPopup bottomSelectionPopup = new BottomSelectionPopup(this);
        bottomSelectionPopup.setTx_title(getString(R.string.text_call_phone));
        for (int i = 0; i < phones.length; i++) {
            if (CommonUtils.checkTelephone(phones[i].trim())) {
                if (i == 0) {
                    bottomSelectionPopup.setTx_1Text(phones[0]);
                } else {
                    bottomSelectionPopup.setTx_2Text(phones[1]);
                }
            }
        }
        bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        CommonUtils.call(mContext, phones[0]);
                        break;
                    case R.id.ll_2:
                        CommonUtils.call(mContext, phones[1]);
                        break;
                }
            }
        });
        bottomSelectionPopup.showPopupWindow();
    }

    @Override
    public void onRefresh() {
        postCommentListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                postCommentListAdapter.getData().clear();
                getData();
                postCommentListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    postCommentListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(PostDetailActivity.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        postCommentListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    private boolean checkGifExist(String message) {
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007F\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(message);
        if (m.find()) {
            return true;
        } else {
            return false;
        }
    }

    // 对文字处理后显示
    private SpannableStringBuilder handler(final TextView gifTextView, String content) {

        if (faceJson == null) {
            faceJson = CommonUtils.getFromAssets2Json("face/face.json", mContext);
        }
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007f\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            for (int i = 0; i < faceJson.length(); i++) {
                try {
                    JSONArray arr = (JSONArray) faceJson.get(i);
                    String faceTemp = arr.get(1).toString();
                    if (faceTemp.equals(m.group())) {
                        String gif = "face/" + arr.get(0);
                        InputStream is = mContext.getAssets().open(gif);
                        sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        is.close();
                    }
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }

    /**
     * 菜单
     */
    private void dropDownMenu() {
        friends = FriendsCache.getInstance(this).getCacheById(postContent.getUser_id());
        String followText = postContent.getIs_follow() == 1 ? getString(R.string.text_unfollow) : getString(R.string.text_follow);
        String collectText = postContent.getFav() == 1 ? getString(R.string.text_remove_fav) : getString(R.string.text_fav);
        String addFriendText = friends == null ? getString(R.string.add_friend) : getString(R.string.text_start_chat);

        if (null == multipeSelectionPopup) {
            multipeSelectionPopup = new MultipeSelectionPopup(this);
            multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
                @Override
                public void onClickItem(View v) {
                    switch (v.getId()) {
                        case R.id.ll_1:
                            executeFollow();
                            break;
                        case R.id.ll_2:
                            executeFav();
                            break;
                        case R.id.ll_3:
                            addFriend();
                            break;
                        case R.id.ll_4:
                            DeletePost();
                            break;
                    }
                }
            });
        }
        if (!postContent.getUser_id().equals(mUserEntity.getData().getUser_id())) {
            multipeSelectionPopup.setTx_1Text(followText);//关注
            multipeSelectionPopup.setTx_2Text(collectText);//收藏
            multipeSelectionPopup.setTx_3Text(addFriendText);//加好友
        } else {
            multipeSelectionPopup.setTx_4Text(getString(R.string.text_delete_post));
        }
        multipeSelectionPopup.showPopupWindow();
    }

    /**
     * 冻结子评论
     */
    private void DeletePostComment() {
        OkHttpUtils.delete().url(URL_POST_DELETE_COMMENT + postComment.getId())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {

            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }


    private void DeletePost() {
        OkHttpUtils.delete().url(URL_POST_DELETE + postContent.getId())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                DeleteCommentEntity deleteCommentEntity = GsonUtil.fromJson(response, DeleteCommentEntity.class);
                if (null != deleteCommentEntity && deleteCommentEntity.getStatus_code() == 200) {
                    multipeSelectionPopup.dismiss();
                    EventBus.getDefault().post(EVENT_DELETE_POST);
                    ShowToast.showShortToast(R.string.alert_delete_success);
                    finish();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    /**
     * 关注用户
     */
    private void executeFollow() {
        swipeLayout.setRefreshing(true);
        String url = URL_FOLLOW_UNFOLLOW + postContent.getUser_id();
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    postContent.setIs_follow(commonEntity.getData().getStatus());
                    multipeSelectionPopup.dismiss();
                    if (commonEntity.getData().getStatus() == 1) {
                        ShowToast.showShortToast(getString(R.string.text_follow_success));
                    } else {
                        ShowToast.showShortToast(getString(R.string.text_follow_cancel));
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                multipeSelectionPopup.dismiss();
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PostDetailActivity.this, status_error);
            }
        });
    }

    /**
     * 收藏
     */
    private void executeFav() {
        swipeLayout.setRefreshing(true);
        String url = URL_FAV_UNFAV + postContent.getId() + "/fav";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CommonEntity commonEntity = GsonUtil.fromJson(response, CommonEntity.class);
                if (commonEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    postContent.setFav(commonEntity.getData().getStatus());
                    multipeSelectionPopup.dismiss();
                    if (commonEntity.getData().getStatus() == 1) {
                        ShowToast.showShortToast(getString(R.string.text_fav_success));
                    } else {
                        ShowToast.showShortToast(getString(R.string.text_fav_cancel));
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                multipeSelectionPopup.dismiss();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PostDetailActivity.this, status_error);
            }
        });
    }

    // 添加好友
    private void addFriend() {
        multipeSelectionPopup.dismiss();
        if (mUserEntity.getData().getUser_id().equals(postContent.getUser_id())) {
            ShowToast.showShortToast(getString(R.string.not_add_myself));
            return;
        }
        if (friends == null) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        //demo use a hardcode reason here, you need let user to input if you like
                        String s = getResources().getString(R.string.Add_a_friend);
                        EMClient.getInstance().contactManager().addContact(postContent.getUser_id() + "", s);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                String s1 = getResources().getString(R.string.send_successful);
                                ShowToast.showShortToast(s1);
                            }
                        });
                    } catch (final Exception e) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                                ShowToast.showShortToast(s2);
                            }
                        });
                    }
                }
            }).start();
        } else {
            startActivity(new Intent(PostDetailActivity.this, ChatActivity.class).putExtra("userId", postContent.getUser_id() + ""));
        }
    }

    private void showRepostView() {
        view_foot.setVisibility(View.VISIBLE);
        view_bottom.setVisibility(View.GONE);
        //获取焦点
        et_content.setFocusable(true);
        et_content.setFocusableInTouchMode(true);
        et_content.requestFocus();
        String hindText = String.format(getString(R.string.text_repost_user), postComment.getUser().getNickname());
        et_content.setHint(hindText);
        imm.showSoftInput(et_content, InputMethodManager.SHOW_FORCED);
    }

    private void hideRepostView() {
        view_foot.setVisibility(View.GONE);
        view_bottom.setVisibility(View.VISIBLE);
        et_content.setFocusable(false);
        et_content.setFocusableInTouchMode(false);
        et_content.setText("");
        InputMethodUtils.closeInputMethod(getApplication(), et_content);
    }


    private void showMultipeSelectionPopup() {
        final MultipeSelectionPopup multipeSelectionPopup = new MultipeSelectionPopup((Activity) mContext);
//        if (subPostComment.getUser_id().equals(SPUtil.getUser().getData().getUser_id()))
//            multipeSelectionPopup.setTx_2Text("删除");
        multipeSelectionPopup.setTx_1Text("复制");
        multipeSelectionPopup.showPopupWindow();
        multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        CommonUtils.copyText(subPostComment.getComment(), getApplication());
                        multipeSelectionPopup.dismiss();
                        break;
                    case R.id.ll_2:
                        //冻结评论
                        DeletePostComment();
                        multipeSelectionPopup.dismiss();
                        break;
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_PARAMS_COMMENT:
                page = 1;
                getData();
                break;
            case EVENT_BUY_POST_SUCCESS:
                postContent.setPurchase(new ArrayList<HomeListEntity.Purchase>());
                initView();
                initData();
                initEvent();
                break;
        }
    }

    private void observe(View view) {
        view.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    //当键盘弹出隐藏的时候会 调用此方法。
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        //获取当前界面可视部分
                        getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                        //获取屏幕的高度
                        int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                        //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                        int heightDifference = screenHeight - r.bottom;
                        if (heightDifference > getBottomKeyboardHeight()) {//有些手机用的是底部虚拟键,所以要大于虚拟键的高度
                            view_foot.setVisibility(View.VISIBLE);
                            view_bottom.setVisibility(View.GONE);
                            //获取焦点
                            et_content.setFocusable(true);
                            et_content.setFocusableInTouchMode(true);
                            et_content.requestFocus();

                        } else {
                            view_foot.setVisibility(View.GONE);
                            view_bottom.setVisibility(View.VISIBLE);
                        }
                    }

                });
    }

    /**
     * @return 底部的虚拟栏的高度
     */
    public int getBottomKeyboardHeight() {
        int screenHeight = DensityUtil.getAccurateScreenDpi(PostDetailActivity.this)[1];
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);//去除底部虚拟栏之后的metric
        int heightDifference = screenHeight - dm.heightPixels;
        return heightDifference;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodUtils.closeInputMethod(getApplication(), et_content);
    }
}
